<template>
  <div class="container" ref="imageDom">
    <div v-html="contentToImg"></div>
    <input type="text" @keydown.enter.native="toImg">
  </div>
</template>
<script>
import html2canvas from 'html2canvas';
export default {
  data() {
    return {
      contentToImg: '点击'
    }
  },
  methods: {
    toImg(content) {
      this.contentToImg = content.data;
      this.$nextTick(() => {
        html2canvas(this.$refs.imageDom, {
          useCORS: true,
          dpi: window.devicePixelRatio * 4,
          scale: 2
        }).then(canvas => {
          this.imgUrl = canvas.toDataURL("image/png");
          console.log(this.imgUrl);
          this.downloadFile(this.title, this.imgUrl)
        })
      })
    },
    downloadFile(fileName, content) {
      let aLink = document.createElement('a');
      let blob = this.base64ToBlob(content);

      // let evt = document.createEvent("HTMLEvents");
      // evt.initEvent("click",true,true);
      let evt = new CustomEvent("HTMLEvent", {
        bubbles: true,
        cancelable: true
      })
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click()
    },
    base64ToBlob(code) {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;

      let uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], { type: contentType });
    }
  }
}
</script>
<style lang="">

</style>